package com.example.tobebigfe.jsbridge

import android.content.Context
import android.webkit.WebView
import org.json.JSONObject

class JSBridgeKVDB(val activity: WebActivity, webView: WebView) : BridgeModuleBase(webView) {

    val preferences = activity.getSharedPreferences("KVDB", Context.MODE_PRIVATE)

    override fun callFunc(func: String, callbackId: String, arg: JSONObject) {
        when (func) {
            "getInt" -> {
                callback(callbackId, getInt(arg.getString("key")))
            }
            "setInt" -> {
                setInt(arg.getString("key"), arg.getInt("value"))
            }
            "getBool" -> {
                callback(callbackId, getBool(arg.getString("key")))
            }
            "setBool" -> {
                setBool(arg.getString("key"), arg.getBoolean("value"))
            }
            "getString" -> {
                callback(callbackId, getString(arg.getString("key")))
            }
            "setString" -> {
                setString(arg.getString("key"), arg.getString("value"))
            }
        }
    }

    fun getInt(key: String): Int {
        return preferences.getInt(key, 0)
    }

    fun setInt(key: String, value: Int) {
        preferences.edit().putInt(key, value).apply()
    }

    fun getBool(key: String): Boolean {
        return preferences.getBoolean(key, false)
    }

    fun setBool(key: String, value: Boolean) {
        preferences.edit().putBoolean(key, value).apply()
    }

    fun getString(key: String): String? {
        return preferences.getString(key, null)
    }

    fun setString(key: String, value: String?) {
        preferences.edit().putString(key, value).apply()
    }

}